<?php

namespace frontend\api\controllers;

use app\models\UserForm;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use Yii;
use frontend\enum\ThirdType;
use frontend\dao\impl\UserDaoImpl;

//Yii::$container->set($class, $definition);

class UserController extends Controller {

    public function behaviors() {
        return [
            'authenticator' => [
                'class' => 'TokenAuth',
                'action' => Yii::$app->controller->action->id
            ],
//            'access' => [
//                'class' => AccessControl::className(),
//                'only' => ['login', 'logout', 'signup', 'test'],
//                'rules' => [
//                    [
//                        'allow' => true,
//                        'actions' => ['login', 'signup'], //游客
//                        'roles' => ['?'],
//                    ],
//                    [
//                        'allow' => true,
//                        'actions' => ['logout', 'test'],
//                        'roles' => ['@'], //登陆的人
//                    ],
//                ],
//            ],
        ];
    }

    public function init() {
        
    }

    public function actionRegister() {

        list($type, $type_uid, $oauth_token, $username, $age, $gender, $signature, $sign, $birthday, $province, $city) = $this->getInput(array('type', 'type_uid', 'oauth_token', 'username', 'age', 'gender', 'signature', 'sign', 'birthday', 'province', 'city'),'post');
        $deviceType = CURRENT_PLATFORM;
        $deviceTypeValue = isset(MtEnum::$device_type[$deviceType]) ? MtEnum::$device_type[$deviceType] : MtEnum::$device_type['PC'];
        $userDm = new UserDm();
        $userDm->setAge($age)
                ->setGender($gender)
                ->setSignature($sign)
                ->setBirthday($birthday)
                ->setProvince($province)
                ->setCity($city)
                ->setUserName($username)
                ->setDevice($deviceTypeValue);
        // if ($deviceType == 'Android') {
        $channel = MT::judgeUserChannel();
        $userDm->setChannel($channel);
        //  }

        $userBindDm = new UserBindDm();
        $userBindDm->setType($type)
                ->setTypeUId($type_uid)
                ->setOauthToken($oauth_token);
        $srv = new UserService();
        switch ($type) {
            case '1':
            case '2':
                $userbo = $srv->mobileRegister($userBindDm, $userDm);
                break;
//            case '4':
//                $userbo = $srv->mobileRegisterByEmail($userBindDm, $userDm);
//                break;
            case '8':
                //  $this->verifyError(BaseError::E_PAY_UNKNOW,'服务器开了小差，请使用微博或QQ注册吧');
                $userbo = $srv->mobileRegisterByUserName($userBindDm, $userDm);
                break;
            default :
                $this->verifyError(BaseError::E_PARAM);
        }


        if ($userbo instanceof BaseError) {
            $this->verifyError($userbo->getCode());
        }
        $userinfo = $userbo->info;
        $uid = $userinfo->uid;
        $access_token = $srv->setLoginToken($userinfo);
        $userinfo = $userinfo->getAttributes();
        $userinfo ['level'] = UserGroupService::simpleCalculateLevel($userinfo ['gid']);
        #判断是否为老师
        $userinfo['isTeacher'] = TeacherService::isTeacher($uid);
        $userinfo['birthday'] = '';
        $userinfo['showid'] = MT::getMemberId($userinfo['uid'], $userinfo['regtime']);
        #开始处理图片
        Yii::import('application.service.user.upload.action.AvatarUpload');
        Yii::import('application.library.upload.MtUpload');
        Yii::import('application.service.photo.srv.AlbumService');
        Yii::import('application.service.user.UserDs');
        Yii::import('application.service.photo.dm.AlbumDm');

        $bhv = new AvatarUpload($uid, 'avatar');
        $upload = new MtUpload($bhv);
        $r = $upload->execute();
        if ($r instanceof BaseError) {
            // $this->verifyError($r->getCode());
        }
        $userinfo['avatar'] = $bhv->getFilePath();
//        $srv = new AlbumService();
//        $albumid = $srv->getDefaultAlbumidByType($uid, AlbumDm::ALBUM_TYPE_ICON);
//        $dms = $bhv->getPhotoInfo();
//        foreach ($dms as $v) {
//            $v->setAlbumid($albumid);
//            $srv->addPhoto($v);
//        }

        $chatAccount = ($r = $chatSrv->register($uid)) instanceof BaseError ? new stdClass() : $r;

        // 发送注册送流量活动链接
        // 活动开始时间 2015-07-23 10:00 活动结束时间 2015-07-31 0:00
//        if(MT::getTime() > 1437616800 && MT::getTime() < 1438272000 && ($deviceTypeValue==1 || ($channel == 'yingyongbao' && (CURRENT_VERSION == '13'||CURRENT_VERSION == '2.1')))){
//        	Yii::import('application.service.freetraffic.srv.FreeTrafficService');
//        	FreeTrafficService::sendUrlToUser($userbo,$access_token);
//        }



        $this->_sendResponse(array('userinfo' => $userinfo, 'access_token' => $access_token, 'chat_account' => $chatAccount), 'register success');
    }

    public function actionLogout() {

        Yii::$app->user->logout();
    }

//    public function actionSignup() {
//
//
//        $model = new UserForm();
//        $model->load(Yii::$app->request->get());
//        $res = $model->validate();
//        print_r($model->getErrors());
//        // var_dump($res);
//    }

    public function actionLogin() {




        $srv = \Yii::$container->get('UserService');

        // $bean =  Yii::$app->request->post();
        list($type, $type_uid, $oauth_token) = $this->getInput(array('type', 'type_uid', 'oauth_token'), 'get');

        switch ($type) {
            case ThirdType::QQ:
            case ThirdType::WeiBo:
            case ThirdType::WeChat:
                $r = $srv->loginByThird($type, $type_uid, $oauth_token);
                break;
            case '4':

                $r = $srv->loginByMobile($type_uid, $oauth_token);
                break;
            case '8':
                $r = $srv->mobileLoginByUserName($type_uid, $oauth_token);
                break;
        }
    }

    public function actionIndex() {
        echo $this->wotest;
        exit;
        return $this->render('index');
    }

    /* 获取参数
     * @param string $name
     * @param string $type get|post|cookie
     * @param bool $bindKey
     */

    protected function getInput($name, $type = '', $bindKey = false) {
        if (is_array($name)) {
            $result = array();
            foreach ($name as $key => $value) {
                $_k = $bindKey ? $value : $key;
                $result[$_k] = $this->getInput($value, $type);
            }
            return $result;
        } elseif ($name) {
            $value = '';
            switch (strtolower($type)) {
                case 'get':
                    $value = Yii::$app->request->get($name);
                    // $value = $_GET[$name];
                    break;
                case 'post':
                    // $value = $_POST[$name];
                    $value = Yii::$app->request->post($name);
                    break;
                case 'cookie':
                    // $value = $_COOKIE[$name];
                    $value = Yii::$app->request->getCookies($name);
                    break;
                default :
                    $value = isset($_REQUEST[$name]) ? $_REQUEST[$name] : '';
            }
            return $value;
        }
        return '';
    }

}
